#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'z417'

import click
from webrunner.common.tools import set_env
from webrunner.common import BASEDIR, L
import os
import time
import sys


@click.group()
@click.option('--log-level', '-L',
              help='set logger level',
              default='info',
              required=False,
              type=click.Choice(['info', 'debug', 'warn', 'error', 'critical'], case_sensitive=False))
@click.version_option(version='4.0.1', message='webrunner   %(version)s')
def cli(log_level):
    """webrunner command"""
    if BASEDIR not in sys.path:
        sys.path.append(BASEDIR)
    L.setLevel(log_level.upper())
    click.echo(
        click.style(
            'start webrunner console log as "{}"'.format(log_level.upper()),
            fg='green'))


@cli.command()
def check():
    """
    check runtime env
    """
    from webrunner.common.environment import Environment
    Environment()  # TODO check more


@cli.command()
@click.option('--pages', '-P',
              help='Set generating path, default [pages.py].',
              default='pages.py',
              required=False,
              type=click.Path())
@click.argument('yml_path', type=click.Path(exists=True), required=True, nargs=1)
def y2p(yml_path, pages):
    """
    parse .yml to .py by template
    """
    yml_path = os.path.join(BASEDIR, yml_path)

    from webrunner.interface import WebRunner
    WebRunner().parse(yml_path, pages)


@cli.command()
@click.option('--report',
              help='junit XML and HTML report name without extension.',
              required=False,
              type=click.Path())
@click.option('--dot-env',
              help='Specify .env file path.',
              required=False,
              type=click.Path())
@click.option('--tag', '-t',
              help='filter tag in DDT cases',
              required=False,
              type=str)
@click.option('--headless', '-H',
              help='set chromedriver running in headless mode',
              default='off',
              required=False,
              type=str)
#   type=click.Choice(['on', 'off'], case_sensitive=False))
@click.option('--pt',
              help="set pytest's commands in quotes",
              required=False,
              type=str)
@click.argument('cases', required=False, nargs=-1)
def rt(cases, report, dot_env, tag, headless, pt):
    """
    [casePath|case.py ...] run testcases.
    """
    set_env(mode=headless)
    msg = '{} is going to run'.format(
        ' '.join(cases)) if cases else 'will run by default'
    msg = '{} {}'.format(pt if pt else '', msg)
    click.echo(click.style(
        msg,
        fg='cyan'))

    if not report:
        report = os.path.join('report', time.strftime(
            '%Y%m%d_%H%M%S', time.localtime(time.time())))
    click.echo(click.style(
        'the report will store in {}'.format(report),
        fg='cyan'))

    if not tag:
        set_env(tag='')
    else:
        set_env(tag=tag.strip())
        click.echo(click.style(
            'tag include "{}" will run'.format(tag), fg='cyan'))

    err_code = 0
    from webrunner.interface import WebRunner
    runner = WebRunner()
    try:
        result = runner.run(cases, report, dot_env, pt)
        err_code |= (0 if result else 1)
    except Exception as e:
        raise e

    # 0 for success and 1 for failed in Linux OS
    return err_code


if __name__ == '__main__':
    cli()
